<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.name"
                placeholder="用户名"
                style="width: 200px"
                class="filter-item"
                @keyup.enter.native="handleFilter" />
      <el-input v-model="listQuery.fileName"
                placeholder="文件名"
                style="width: 200px"
                class="filter-item"
                @keyup.enter.native="handleFilter" />

      <el-button v-waves
                 class="filter-item"
                 type="primary"
                 icon="el-icon-search"
                 @click="handleFilter">
        搜索
      </el-button>
    </div>

    <el-table :key="tableKey"
              v-loading="listLoading"
              :data="list"
              border
              fit
              highlight-current-row
              style="width: 100%"
              @sort-change="sortChange">
      <el-table-column label="ID"
                       prop="id"
                       sortable="custom"
                       align="center"
                       width="80"
                       :class-name="getSortClass('id')">
        <template slot-scope="{ row }">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="用户ID"
                       prop="name"
                       align="center"
                       width="150">
        <template slot-scope="{ row }">
          <span>{{ row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="文件路径"
                       prop="path"
                       align="center"
                       width="330">
        <template slot-scope="{ row }">
          <span>{{ row.path }}</span>
        </template>
      </el-table-column>
      <el-table-column label="文件名"
                       prop="fileName"
                       align="center"
                       width="350">
        <template slot-scope="{ row }">
          <span>{{row.fileName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="审核状态"
                       prop="examine"
                       align="center"
                       width="130">
        <template slot-scope="{ row }">
          <el-tag :type="stateType[row.examine]">
            <span>{{ stateMap[row.examine] }}</span>
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="上传时间"
                       width="250px"
                       align="center">
        <template slot-scope="{ row }">
          <span>{{ row.createTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作"
                       align="center"
                       width="350"
                       class-name="small-padding fixed-width">
        <template slot-scope="{ row, $index }">
          <el-button type="info"
                     size="mini"
                     @click="openPreview(row)">
            查看文件
          </el-button>
          <el-button type="primary"
                     size="mini"
                     @click="examine({id:row.id,state:1})">
            审核通过
          </el-button>
          <el-button type="warning"
                     size="mini"
                     @click="examine({id:row.id,state:2})">
            审核拒绝
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0"
                :total="total"
                :page.sync="listQuery.page"
                :limit.sync="listQuery.limit"
                @pagination="getList" />
    <el-dialog title="文件预览"
               :visible="showDoc == true || showPdf == true || showImg == true"
               :width="fileWidth"
               :before-close="closePreviewClick"
               class="dialog-div-pre-style"
               center
               append-to-body>
      <div v-if="showDoc == true">
        <iframe frameborder="0"
                :src="
            'https://view.officeapps.live.com/op/view.aspx?src=' + this.fileUrl
          "
                width="100%"
                height="800px">
        </iframe>
      </div>
      <div v-else-if="showPdf == true"
           style="justify-content: center; align-items: center">
        <embed :src="pdfUrl"
               style="width: 100%; height: 80vh" />
      </div>
      <div v-else-if="showImg == true"
           style="
          justify-content: center;
          align-items: center;
          min-width: 40px;
          min-height: 40px;
        ">
        <img :src="imagesUrl"
             alt=""
             style="width: 100%; height: auto" />
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  fetchList,
  fetchPv,
  createArticle,
  updateArticle,
  delUser,
  preview
} from "@/api/file";
import waves from "@/directive/waves"; // waves directive
import { parseTime } from "@/utils";
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination

export default {
  name: "FileExamine",
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter (status) {
      const statusMap = {
        published: "success",
        draft: "info",
        deleted: "danger",
      };
      return statusMap[status];
    },
    typeFilter (type) {
      return calendarTypeKeyValue[type];
    },
  },
  data () {
    return {
      // 文件预览
      showDoc: false,
      showPdf: false,
      showImg: false,
      fileUrl: "",
      imagesUrl: "",
      pdfUrl: "",
      fileWidth: "min-width = 300px",
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        name: null,
        fileName: null
      },
      importanceOptions: [1, 2, 3],
      stateMap: {
        0: '等待审核',
        1: '审核已通过',
        2: '审核未通过',
        3: '未知'
      },
      stateType: {
        0: 'warning',
        1: 'success',
        2: 'danger',
        3: 'info'
      },
      showReviewer: false,
      temp: {
        id: undefined,
        importance: 1,
        remark: "",
        timestamp: new Date(),
        title: "",
        type: "",
        status: "published",
      },
      dialogFormVisible: false,
      dialogStatus: "",
      textMap: {
        update: "Edit",
        create: "Create",
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        type: [
          { required: true, message: "type is required", trigger: "change" },
        ],
        timestamp: [
          {
            type: "date",
            required: true,
            message: "timestamp is required",
            trigger: "change",
          },
        ],
        title: [
          { required: true, message: "title is required", trigger: "blur" },
        ],
      },
      downloadLoading: false,
    };
  },
  created () {
    this.getList();
  },
  methods: {
    //审核文件
    examine (data) {
      updateArticle(data).then(data => {
        this.getList();
      })
    },
    //预览文件
    openPreview (row) {
      preview({ fileName: `${row.path}${row.fileName}` }).then((res) => {
        let url = res.data;
        if (
          url.indexOf("doc") != -1 ||
          url.indexOf("docx") != -1 ||
          url.indexOf("xsl") != -1 ||
          url.indexOf("xlsx") != -1 ||
          url.indexOf("ppt") != -1
        ) {
          this.fileWidth = "80%";
          this.showDoc = true;
          this.fileUrl = url;
        } else if (url.indexOf("pdf") != -1) {
          this.fileWidth = "80%";
          this.pdfUrl = url;
          this.showPdf = true;
        } else if (
          url.indexOf("jpg") != -1 ||
          url.indexOf("png") != -1 ||
          url.indexOf("jpeg") != -1
        ) {
          this.showImg = true;
          this.imagesUrl = url;
          let image = new Image();
          image.src = url;
          image.onload = () => {
            this.fileWidth = image.width + "px";
          };
        } else {
          this.$message("当前文件暂不支持预览");
        }
      });
    },
    closePreviewClick () {
      if (this.showDoc == true) {
        this.showDoc = false;
      } else if (this.showPdf == true) {
        this.showPdf = false;
      } else if (this.showImg == true) {
        this.showImg = false;
      }
    },
    getList () {
      this.listLoading = true;
      fetchList(this.listQuery).then((response) => {
        this.list = response.data.items;
        this.total = response.data.total;
        setTimeout(() => {
          this.listLoading = false;
        }, 1.5 * 1000);
      });
    },
    handleFilter () {
      this.listQuery.page = 1;
      this.getList();
    },
    handleModifyStatus (row, status) {
      this.$message({
        message: "操作Success",
        type: "success",
      });
      row.status = status;
    },
    sortChange (data) {
      const { prop, order } = data;
      if (prop === "id") {
        this.sortByID(order);
      }
    },
    sortByID (order) {
      if (order === "ascending") {
        this.listQuery.sort = "+id";
      } else {
        this.listQuery.sort = "-id";
      }
      this.handleFilter();
    },
    resetTemp () {
      this.temp = {
        id: undefined,
        importance: 1,
        remark: "",
        timestamp: new Date(),
        title: "",
        status: "published",
        type: "",
      };
    },
    handleCreate () {
      this.resetTemp();
      this.dialogStatus = "create";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    createData () {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          this.temp.id = parseInt(Math.random() * 100) + 1024; // mock a id
          this.temp.author = "vue-element-admin";
          createArticle(this.temp).then(() => {
            this.list.unshift(this.temp);
            this.dialogFormVisible = false;
            this.$notify({
              title: "成功",
              message: "添加成功",
              type: "success",
              duration: 2000,
            });
          });
        }
      });
    },
    handleUpdate (row) {
      this.temp = Object.assign({}, row); // copy obj
      this.temp.timestamp = new Date(this.temp.timestamp);
      this.dialogStatus = "update";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    updateData () {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp);
          // tempData.timestamp = +new Date(tempData.timestamp); // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
          updateArticle(tempData).then(() => {
            const index = this.list.findIndex((v) => v.id === this.temp.id);
            this.list.splice(index, 1, this.temp);
            this.dialogFormVisible = false;
            this.$notify({
              title: "Success",
              message: "Update Successfully",
              type: "success",
              duration: 2000,
            });
          });
        }
      });
    },
    handleDelete (row, index) {
      delUser({ 'id': row.id }).then(() => {
        this.$notify({
          title: "成功",
          message: "删除成功",
          type: "success",
          duration: 2000,
        })
        this.list.splice(index, 1);
      }
      )

    },
    handleFetchPv (pv) {
      fetchPv(pv).then((response) => {
        this.pvData = response.data.pvData;
        this.dialogPvVisible = true;
      });
    },
    handleDownload () {
      this.downloadLoading = true;
      import("@/vendor/Export2Excel").then((excel) => {
        const tHeader = ["id", "用户ID", "注册时间", "邮箱", "角色", "状态"];
        const filterVal = [
          "id",
          "name",
          "createDate",
          "email",
          "auth",
          "state",
        ];
        const data = this.formatJson(filterVal);
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: "table-list",
        });
        this.downloadLoading = false;
      });
    },
    formatJson (filterVal) {
      return this.list.map((v) =>
        filterVal.map((j) => {
          if (j === "timestamp") {
            return parseTime(v[j]);
          } else {
            return v[j];
          }
        })
      );
    },
    getSortClass: function (key) {
      const sort = this.listQuery.sort;
      return sort === `+${key}` ? "ascending" : "descending";
    },
  },
};
</script>
